<template>
  <div class="container">
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="add">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-button type="warning" @click="edit">编辑</el-button>
        <el-select v-model="selectedFilter" placeholder="请选择状态" style="width: 200px;">
          <el-option label="启用" value="enabled"></el-option>
          <el-option label="禁用" value="disabled"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" style="width: 200px;" />
        <el-button type="info" @click="query">查询</el-button>
        <el-button type="info" @click="query">重置</el-button>
      </div>
      <el-table :data="tableData" border class="eltable">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="ckpd_code" label="仓库盘点编号"></el-table-column>
        <el-table-column prop="ckpd_type" label="仓库盘点类型"></el-table-column>
        <el-table-column prop="ck_name" label="仓库名称"></el-table-column>
        <el-table-column prop="ckpd_jhpdsj" label="计划盘点时间"></el-table-column>
        <el-table-column prop="ckpd_bz" label="仓库盘点备注"></el-table-column>
        <el-table-column prop="ckpd_ykzsl" label="盈亏总数"></el-table-column>
        <el-table-column prop="user_uname" label="创建人"></el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="text" @click="bj(row)">编辑</el-button>
            <el-button type="text" @click="pd(row)">盘点</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper">
      </el-pagination>
    </div>
  </div>
  <!-- 添加 -->
  <el-dialog v-model="dialogVisible" title="添加" height="800">
    <el-form :model="form" :inline="true" class="demo-form-inline">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="盘点类型">
            <el-select v-model="form.ckpd_type" placeholder="选择调拨类型" style="width: 200px;" @change="handleLeaderChange">
              <el-option v-for="item in options" :key="item.label" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划盘点时间">
            <el-date-picker v-model="form.ckpd_jhpdsj" type="date" placeholder="Pick a day" :size="size" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点仓库">
            <el-select v-model="form.ckpd_ck" placeholder="选择盘点仓库" style="width: 200px" @change="handleLeaderChange">
              <el-option v-for="item in cktableData" :key="item.ck_code" :label="item.ck_name" :value="item.ck_code"
                @click="cxkc(item.ck_code)" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="备注">
            <el-input v-model="form.ckpd_bz"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="kctableData" border class="eltable">
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="kq_name" label="库区">
        <!-- <template #default="{ row }">
            <el-input v-model="row.kq_name"></el-input>
          </template> -->
      </el-table-column>
      <el-table-column prop="kw_name" label="库位"></el-table-column>
      <el-table-column prop="wl_code" label="物料编码"></el-table-column>
      <el-table-column prop="wl_name" label="物料名称"></el-table-column>
      <el-table-column prop="dictionary_name" label="物料类型"></el-table-column>
      <el-table-column prop="wl_size" label="规格型号"></el-table-column>
      <el-table-column prop="dw_name" label="物料单位"></el-table-column>
      <el-table-column prop="kc_sl" label="账面库存数量"></el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addqr">确 定</el-button>
    </span>
  </el-dialog>
  <!-- 盘点 -->
  <el-dialog v-model="pddialogVisible" title="盘点" height="800">
    <el-table :data="ckpdxxtableData" border class="eltable">
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="kq_name" label="库区"></el-table-column>
      <el-table-column prop="kw_name" label="库位"></el-table-column>
      <el-table-column prop="wl_code" label="物料编码"></el-table-column>
      <el-table-column prop="ckpdxx_wlmc" label="物料名称"></el-table-column>
      <el-table-column prop="ckpdxx_wllx" label="物料类型"></el-table-column>
      <el-table-column prop="ckpdxx_ggxh" label="规格型号"></el-table-column>
      <el-table-column prop="ckpdxx_wldw" label="物料单位"></el-table-column>
      <el-table-column prop="ckpdxx_zmkcsl" label="账面库存数量"></el-table-column>
      <el-table-column prop="ckpdxx_pdzsl" label="盘点数量" width="100">
        <template #default="{ row }">
          <el-input v-model="row.ckpdxx_pdzsl" placeholder="请输入数量" type="number" min="0" @input="handleInput(row)" />
        </template>
      </el-table-column>
      <el-table-column prop="ckpdxx_ykzsl" label="盈亏数量"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <span v-if="row.ckpdxx_state == 1">
            <el-button type="text" @click="wcpd(row)">完成盘点</el-button>
          </span>
          <span v-if="row.ckpdxx_state == 2">
            <el-button type="text" @click="pdtz(row)">盘点调整</el-button>
          </span>
          <span v-if="row.ckpdxx_state == 3">
            <el-button type="text" @click="qxtz(row)" style="color: red;">取消调整</el-button>
          </span>
          <span v-if="row.ckpdxx_state == 4">
            <el-button type="text" style="color: green;">操作完成</el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @current-change="handleCurrentChange1" :current-page="currentPage2" :page-size="pageSize2"
      :total="totalItems2" layout="total, prev, pager, next, jumper">
    </el-pagination>
    <span slot="footer" class="dialog-footer">
      <el-button @click="pddialogVisible = false">取 消</el-button>
    </span>
  </el-dialog>
  <!-- 编辑 -->
  <el-dialog v-model="xgdialogVisible" title="编辑" height="800">
    <el-form :model="xgform" :inline="true" class="demo-form-inline">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="盘点类型">
            <el-input v-model="xgform.ckpd_type"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划盘点时间">
            <el-date-picker v-model="xgform.ckpd_jhpdsj" type="date" placeholder="Pick a day" :size="size" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点仓库">
            <el-select disabled v-model="xgform.ckpd_ck" placeholder="选择盘点仓库" style="width: 200px"
              @change="handleLeaderChange">
              <el-option v-for="item in cktableData" :key="item.ck_code" :label="item.ck_name" :value="item.ck_code"
                @click="cxkc(item.ck_code)" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="备注">
            <el-input v-model="xgform.ckpd_bz"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="xgtableData" border class="eltable">
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="kq_name" label="库区">
        <!-- <template #default="{ row }">
            <el-input v-model="row.kq_name"></el-input>
          </template> -->
      </el-table-column>
      <el-table-column prop="kw_name" label="库位"></el-table-column>
      <el-table-column prop="wl_code" label="物料编码"></el-table-column>
      <el-table-column prop="wl_name" label="物料名称"></el-table-column>
      <el-table-column prop="dictionary_name" label="物料类型"></el-table-column>
      <el-table-column prop="wl_size" label="规格型号"></el-table-column>
      <el-table-column prop="dw_name" label="物料单位"></el-table-column>
      <el-table-column prop="kc_sl" label="账面库存数量"></el-table-column>
    </el-table>
    <el-pagination @current-change="handleCurrentChange" :current-page="currentPage1" :page-size="pageSize1"
      :total="totalItems1" layout="total, prev, pager, next, jumper">
    </el-pagination>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="bjqr">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { ref, reactive, router, computed } from 'vue';
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    const searchKey = ref('');
    const treeData = ref([]);
    const defaultProps = {
      children: 'children',
      label: 'label',
    };
    //获取登录角色数据
    const uid = computed(() => {
      return sessionStorage.getItem('u');
    })
    let yhid = reactive({
      id: uid
    })
    let lx = ref('')
    const tableData = ref([]);
    const cktableData = ref([]);
    const kctableData = ref([]);
    const xgtableData = ref([]);
    const ckpdxxtableData = ref([]);
    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const dialogVisible = ref(false)
    const pddialogVisible = ref(false)
    const xgdialogVisible = ref(false)
    const pageSize = ref(10);
    const totalItems = ref(3);
    const currentPage1 = ref(1);
    const pageSize1 = ref(2);
    const totalItems1 = ref(0);
    const currentPage2 = ref(1);
    const pageSize2 = ref(2);
    const totalItems2 = ref(0);
    const currentPage3 = ref(1);
    const pageSize3 = ref(2);
    const totalItems3 = ref(0);
    let form = reactive({
      ckpd_type: '',
      ckpd_jhpdsj: '',
      ckpd_ck: '',
      ckpd_bz: '',
      uid: yhid.id
    })
    let xgform = reactive({
      ckpd_code: '',
      ckpd_type: '',
      ckpd_jhpdsj: '',
      ckpd_ck: '',
      ckpd_bz: '',
      uid: yhid.id
    })

    function add() {
      dialogVisible.value = true
    };
    async function SX() {
      const response = await axios.get('/api/WMS_CKPD/GetCXWMS_CKPD?PageNumber=' + currentPage.value + '&PageSize=' + pageSize.value);
      tableData.value = response.data.cXWMS_CKPDs
      totalItems.value = response.data.zon
      const response1 = await axios.get('/api/Wbd_ck/Wbd_Ck');
      cktableData.value = response1.data
    }
    SX();
    async function cxkc(code) {
      const response = await axios.get('/api/WMS_KC/GetFYCXWMS_KC?PageNumber=' + currentPage1.value + '&PageSize=' + pageSize1.value + '&code=' + code);
      kctableData.value = response.data.cXWMS_KCs
      totalItems1.value = response.data.zon
    }
    async function addqr() {
      try {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
        const day = String(now.getDate()).padStart(2, '0'); // 补零

        // 生成四位随机数
        const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

        // 拼接时间字符串和随机数
        const formattedTime = `${year}${month}${day}`;
        let id = `CKPD${formattedTime}${randomNumber}`
        const response = await axios.post('/api/WMS_CKPD/PostWMS_CKPD', {
          ckpd_code: id,
          ckpd_type: form.ckpd_type,
          ckpd_ck: form.ckpd_ck,
          ckpd_jhpdsj: form.ckpd_jhpdsj,
          ckpd_bz: form.ckpd_bz,
          create_by: form.uid
        });
        if (response.data) {
          for (const team of kctableData.value) {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
            const day = String(now.getDate()).padStart(2, '0'); // 补零

            // 生成四位随机数
            const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

            // 拼接时间字符串和随机数
            const formattedTime = `${year}${month}${day}`;
            let code = `CKPDXX${formattedTime}${randomNumber}`
            const response = await axios.post('/api/WMS_CKPDXX/PostWMS_CKPDXX', {
              ckpdxx_code: code,
              ckpd_code: id,
              ck_code: form.ckpd_ck,
              kq_code: team.kq_code,
              kw_code: team.kw_code,
              wl_code: team.wl_code,
              ckpdxx_wlmc: team.wl_name,
              ckpdxx_wllx: team.dictionary_name,
              ckpdxx_wldw: team.dw_name,
              ckpdxx_ggxh: team.wl_size,
              ckpdxx_zmkcsl: team.kc_sl,
              ckpdxx_dj: team.wl_dj
            });
          }
          ElMessage.success("成功")
          SX()
          dialogVisible.value = false
        }
      } catch (error) {
        console.error("请求错误:", error);
        ElMessage.error("服务器错误，请稍后重试。");
      }
    }
    let pdrow=ref([])
    async function pd(row) {
      pdrow.value=row
      lx.value = row.ckpd_type
      pddialogVisible.value = true
      const response = await axios.get('/api/WMS_CKPDXX/GetCXWMS_CKPDXX?PageNumber=' + currentPage2.value + '&PageSize=' + pageSize2.value + '&code=' + row.ckpd_code);
      ckpdxxtableData.value = response.data.cXWMS_CKPDXXs
      totalItems2.value = response.data.zon
    }
    async function bj(row) {
      xgform.ckpd_code = row.ckpd_code
      xgform.ckpd_type = row.ckpd_type,
        xgform.ckpd_jhpdsj = row.ckpd_jhpdsj,
        xgform.ckpd_ck = row.ckpd_ck,
        xgform.ckpd_bz = row.ckpd_bz
      const response = await axios.get('/api/WMS_KC/GetFYCXWMS_KC?PageNumber=' + currentPage3.value + '&PageSize=' + pageSize3.value + '&code=' + row.ckpd_ck);
      xgtableData.value = response.data.cXWMS_KCs
      totalItems3.value = response.data.zon
      xgdialogVisible.value = true
    }
    async function bjqr() {
      const response = await axios.put('/api/WMS_CKPD/UpdateWMS_CKPD', {
        ckpd_code: xgform.ckpd_code,
        ckpd_type: xgform.ckpd_type,
        ckpd_jhpdsj: xgform.ckpd_jhpdsj,
        ckpd_bz: xgform.ckpd_bz,
        update_by: xgform.uid
      });
      if (response.data) {
        ElMessage.success('成功')
        xgdialogVisible.value = false
      }
    }
    const query = () => {
      // 查询逻辑  
      console.log('Querying with:', searchTable.value);
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      SX()
      // 分页逻辑  
      console.log('Current page:', page);
    };
    const handleCurrentChange1 = (page) => {
      currentPage2.value = page;
      pd(pdrow.value)
    };
    
    async function wcpd(row) {
      try {
        const response = await axios.put('/api/WMS_CKPDXX/UpdateWMS_CKPDXX?pdsl=' + row.ckpdxx_pdzsl + '&sl=' + row.ckpdxx_ykzsl + '&code=' + row.ckpdxx_code)
        if (response.data) {
          const response = await axios.put('/api/WMS_CKPD/UpdateWMS_CKPDSL?uid=' + yhid.id + '&sl=' + row.ckpdxx_ykzsl + '&code=' + row.ckpd_code)
          if (response.data) {
            ElMessage.success('成功')
            pd(pdrow.value)
          }
        }
      } catch (error) {
        console.error("请求错误:", error);
        ElMessage.error("服务器错误，请稍后重试。");
      }
    }
    async function pdtz(row) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
      const day = String(now.getDate()).padStart(2, '0'); // 补零

      // 生成四位随机数
      const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

      // 拼接时间字符串和随机数
      const formattedTime = `${year}${month}${day}`;
      let code = `pdtz${formattedTime}${randomNumber}`
      console.log(lx.value)
      try {
        const response = await axios.post('/api/WMS_PDTZ/PostWMS_PDTZ', {
          pdtz_code: code,
          pdtz_pdlx: lx.value,
          ckpdxx_code: row.ckpdxx_code,
          ckpd_code: row.ckpd_code,
          ck_code: row.ck_code,
          kq_code: row.kq_code,
          kw_code: row.kw_code,
          wl_code: row.wl_code,
          pdtz_wlmc: row.ckpdxx_wlmc,
          pdtz_wllx: row.ckpdxx_wllx,
          pdtz_wldw: row.ckpdxx_wldw,
          pdtz_ggxh: row.ckpdxx_ggxh,
          pdtz_zmkcsl: row.ckpdxx_zmkcsl,
          pdtz_pdzsl: row.ckpdxx_pdzsl,
          pdtz_wldj: row.ckpdxx_wldj,
          pdtz_ykzsl: row.ckpdxx_ykzsl,
        })
        if (response.data) {
          const response = await axios.put('/api/WMS_CKPDXX/UpdateWMS_CKPDZT?code=' + row.ckpdxx_code + '&pdtzcode=' + code + '&state=3')
          if (response.data) {
            ElMessage.success('成功')
            pd(pdrow.value)
          }
        }
      } catch (error) {
        console.error("请求错误:", error);
        ElMessage.error("服务器错误，请稍后重试。");
      }
    }
    async function qxtz(row) {
      console.log(row)
      try {
        const response = await axios.delete('/api/WMS_PDTZ/DeleteCXWMS_PDTZ?code=' + row.pdtz_code)
        if (response.data) {
          const response = await axios.put('/api/WMS_CKPDXX/UpdateWMS_CKPDZT?code=' + row.ckpdxx_code + '&pdtzcode=NULL&state=2')
          if (response.data) {
            ElMessage.success('成功')
            pd(pdrow.value)
          }
        }
      } catch (error) {
        console.error("请求错误:", error);
        ElMessage.error("服务器错误，请稍后重试。");
      }
    }
    // 确保所有函数都被返回  
    return {
      searchKey,
      treeData,
      defaultProps,
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      add,
      query,
      handleCurrentChange,
      handleCurrentChange1,
      dialogVisible,
      form,
      cktableData,
      currentPage1,
      pageSize1,
      totalItems1,
      currentPage2,
      pageSize2,
      totalItems2,
      currentPage3,
      pageSize3,
      totalItems3,
      cxkc,
      kctableData,
      addqr,
      ckpdxxtableData,
      pd,
      pddialogVisible,
      bj,
      xgtableData,
      xgform,
      xgdialogVisible,
      bjqr,
      wcpd,
      pdtz,
      qxtz,
      options: [{
        value: 1,
        label: '期初盘点'
      }, {
        value: 2,
        label: '存货盘点'
      }, {
        value: 3,
        label: '期末盘点'
      }],
    };
  },
  methods: {
    handleInput(row) {
      row.ckpdxx_ykzsl = (row.ckpdxx_pdzsl - row.ckpdxx_zmkcsl) * row.ckpdxx_wldj
    },
  }
};
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 95%;
}

.sidebar {
  height: 100%;

}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 95%;
  font-size: 80%;
}

.letree {
  height: 100%;
}
</style>